package com.tucc.hello.leetcode.no1_400.no1_200.no21_40.no35;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1, 3};
        int target = 0;
        System.out.println(solution.searchInsert2(nums, target));
    }


    public int searchInsert2(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        int ans = 0;
        while (l < r) {
            int mid = (l + r) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                ans = mid;
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        int m = Math.min(l, r);
        if(m < 0){
            return 0;
        }
        if (target > nums[m]) {
            ans = m + 1;
        } else {
            ans = m;
        }
        return ans;
    }

    public int searchInsert(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        int ans = nums.length;
        while (l <= r) {
            int mid = (l + r) / 2;
            if (nums[mid] >= target) {
                ans = mid;
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return ans;
    }
}
